package com.example.studentdemo.service.impl;

import com.example.studentdemo.properties.MinioProperties;
import com.example.studentdemo.service.AvatarService;
import io.minio.*;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class AvatarServiceImpl implements AvatarService {
    private final MinioClient minioClient;
    private final MinioProperties props;

    @Override
    public String uploadAvatar(MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String bucket = props.getBucket();
        // 建桶（不存在时）
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!exists) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            String policy = """
                    {"Version":"2012-10-17","Statement":[
                        {"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}
                    ]}""".formatted(bucket);
            minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder().bucket(bucket).config(policy).build());
        }

        // 生成对象名  yyyyMMdd/uuid.ext
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String obj = date + "/" + UUID.randomUUID() + "." + ext;

        // 上传
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucket)
                        .object(obj)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(Optional.ofNullable(file.getContentType())
                                .orElse("application/octet-stream"))
                        .build());

        // 拼装永久访问 URL（MinIO 直接读）
        return props.getEndpoint() + "/" + bucket + "/" + obj;
    }
}
